package com.bjb.vr.remote.ws.rabbitmq.handler.impl;

import com.alibaba.fastjson.JSONObject;
import com.bjb.vr.common.dto.ResGroup;
import com.bjb.vr.common.service.ResGroupService;
import com.bjb.vr.common.utils.RedisUtil;
import com.bjb.vr.remote.ws.rabbitmq.constants.MessageActionConstants;
import com.bjb.vr.remote.ws.rabbitmq.entity.RabbitWebSocketMsg;
import com.bjb.vr.remote.ws.rabbitmq.handler.MessageHandler;
import com.bjb.vr.remote.ws.redis.constants.RedisConstants;
import com.bjb.vr.remote.ws.websocket.vo.Message;
import com.bjb.vr.remote.ws.websocket.websocket.WebSocketMsgHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @version 1.0.0
 * @description:
 * @author: caihaibo
 * @createDate: 2022/3/29
 */
@Slf4j
@Component
public class MuteMessageHandler implements MessageHandler {

    @Autowired
    ResGroupService resGroupService;

    @Autowired
    RedisUtil redisUtil;

    final String  LOCK_KEY = "res_group_class_state";


    @Override
    public void process(RabbitWebSocketMsg rabbitWebSocketMsg) {

        String dbLockKey = RedisConstants.WEBSOCKET_DB_OP_LOCK_KEY + LOCK_KEY+ rabbitWebSocketMsg.getGroupCode();


        JSONObject jsonObject = JSONObject.parseObject(rabbitWebSocketMsg.getMsg());

        Message message = JSONObject.toJavaObject(jsonObject, Message.class);

        if(message.getAction().equals(MessageActionConstants.MESSAGE_ACTION_MUTE)){
            log.info("处理静音信息");
            WebSocketMsgHandler.sendAllClient(rabbitWebSocketMsg);

            String value = String.valueOf(System.currentTimeMillis());
            if(redisUtil.lock(dbLockKey,value,RedisConstants.WEBSOCKET_DB_OP_LOCK_KEY_EXPIRE_TIME)) {

                ResGroup resGroup = new ResGroup();
                resGroup.setGroupCode(rabbitWebSocketMsg.getGroupCode());
                resGroup.setSoundState(2);

                resGroupService.updateResGroupByGroupCode(resGroup);
                redisUtil.unlock(dbLockKey, value);
            }
        }

    }
}
